<template>
  <div
    ref="buttonRef"
    id="request-interceptor-float-btn"
    @click="handleClick"
    :style="{ transform: `translate3d(${x}px, ${y}px, 0)` }"
  >
    🔧
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { useDraggable } from '@vueuse/core'

const emit = defineEmits(['click'])

const buttonRef = ref()

// 使用 vueuse 的 useDraggable
const { x, y, isDragging } = useDraggable(buttonRef, {
  initialValue: { x: 0, y: 0 }, // 保持默认位置
  preventDefault: true,
  stopPropagation: true,
  onStart: () => {
    // 只在按钮上禁用文本选择，不影响整个页面
    if (buttonRef.value) {
      buttonRef.value.style.cursor = 'grabbing'
    }
  },
  onEnd: () => {
    // 恢复按钮样式
    if (buttonRef.value) {
      buttonRef.value.style.cursor = 'move'
    }

    // 延迟一点时间再允许点击，避免拖拽结束后立即触发点击
    nextTick(() => {
      setTimeout(() => {
        // 确保拖拽结束后的状态正确
      }, 100)
    })
  }
})

const handleClick = (e) => {
  // 如果正在拖拽，不触发点击事件
  if (isDragging.value) {
    e.preventDefault()
    e.stopPropagation()
    return
  }

  e.stopPropagation()
  emit('click')
}
</script>

<style scoped>
#request-interceptor-float-btn {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  cursor: move;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.4);
  z-index: 999999;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  border: 2px solid rgba(255, 255, 255, 0.2);
  touch-action: none;
}

#request-interceptor-float-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6);
  background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
}

#request-interceptor-float-btn:active {
  transform: scale(0.95);
}
</style>
